Ext.onReady(function(){
  var Tree = Ext.tree;
   var selNode = null;
    var tree ;
    var ipr = 0;
    var bipr = true;
     Ext.QuickTips.init();
      var form = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 55,
        defaultType: 'textfield',
        items: [{
            fieldLabel: '分类名称',
            maxLengthText:'长度不要超过200个字符',
            id:'sortName',
            allowBlank:false,
            blankText:'必填项',
            name: 'sortName',
            anchor:'100%'  // anchor width by percentage
        },new Ext.form.NumberField({
            fieldLabel: '分类序号',
            id:'siblingSeq',
            maxLength:5,
            value:100,
            name: 'siblingSeq',
            anchor: '100%'  // anchor width by percentage
        })]
    });

	var w=new Ext.Window({
          // contentEl:"win",//主体显示的html元素，也可以写为el:"win"
           width:250,
           height:150,
           closable:false,
           title:"添加分类",
			items: form,
			buttons: [{
				text: '保存',
				handler:function()
				{
				  if(!form.form.isValid())
           				Ext.MessageBox.alert("提示!", "请正确填写表单!");
           		  else{
           			w.hide();
           			if(ipr == 1)
           				addShowResultText(form.items.items[0].getValue(),form.items.items[1].getValue());
           			else if(ipr == 2)
           				modiShowResultText(form.items.items[0].getValue(),form.items.items[1].getValue());
					cleanForm();
					}    
					 bipr = true; 
						       ipr = 0; 
				}
				 
			},{    
				text: '取消',
				handler:function()
				{
				w.hide();
				cleanForm();
				  bipr = true; 
				  ipr = 0; 
				}
			}]
        });
        
        /***清楚form中数据***/
      function cleanForm(){
	      form.items.items[0].setValue('');
	      form.items.items[1].setValue('');
      }
   
// shorthand
 var accordion = new Ext.Panel({
                region:'center',
                margins:'5 0 5 5',
                split:true,
                width: 210,
                margins:'0 0 0 0',
                autoScroll:true,
                border:false,
                html:'<div id="leftTree"></div>'
            });

            var viewport = new Ext.Panel({
            	renderTo:'layout-borderlayout-main',
                layout:'border',
                margins:'0 0 0 0',
                autoWidth:true,
                height:600,
                items:[
                    accordion]
            });
  	/**
	 * 右键菜单 
	 */
  var ctxMenu = new Ext.menu.Menu({
        id:'copyCtxs',
        items: [{
                id:'orgadd',
                handler:sortAdd,
                cls:'expand-all',
                text:'增加'
            },{
                id:'orgmodi',
                handler:sortModi,
                cls:'collapse-all',
                text:'修改'
            }
            ,{
                id:'orgdel',
                handler:sortdel,
                cls:'collapse-all',
                text:'删除'
            }]
    });
       var win;
     /***添加分类**/
    function sortAdd(){
       if(selNode == null)
       	return;
       	 //Ext.MessageBox.prompt('添加分类', '请输入分类名称:', addShowResultText);
       	 if(bipr)
       	 {
       	  w.show();
       	  ipr=1; 
       	    bipr = false; 
       	  } 
       	  //alert(""+selNode.attributes.siblingSeq);
    }
    /**添加分类**/
    function addShowResultText(text,siblingSeq){
    		sortAjax("tagTree.htm",{id:selNode.id,tagType:selNode.attributes.tagType,action:'addSort',sortName:text,siblingSeq:siblingSeq},addSu,sortFail);
    }
    /***xxigai ********/
     function modiShowResultText(text,siblingSeq){
      if(text !=selNode.text)
    	{
    	selNode.setText(text);
    	selNode.attributes.siblingSeq = siblingSeq;
    	sortAjax("tagTree.htm",{id:selNode.id,action:'editSort',sortName:text,siblingSeq:siblingSeq},addSuE,sortFail);
    	}
    }
    /**xiug chengg**/
    function addSuE(){}
    function delShowResultText(a,b){
     if(a=='yes')
     {
      root.removeChild(selNode);
      sortAjax("tagTree.htm",{id:selNode.id,action:'delSort'},function(){},sortFail);
      }
    }

    function addSu(request){
	    var obj = eval("["+request.responseText+"]");
	    if(obj[0].success)
	     {
	       fcm(obj[0].data[0].id,obj[0].data[0].name,obj[0].data[0].siblingSeq);
	     }
	     else alert("添加失败!");
    }
    function sortFail(){alert("操作失败!");}
    function sortModi(node){ 
    if(selNode == null)
       	return;
       //	 Ext.MessageBox.prompt('修改分类', '请输入分类名称:', modiShowResultText,null,null,selNode.text);
      	 if(bipr)
       	 {
          form.items.items[0].setValue(selNode.text);
	      form.items.items[1].setValue(selNode.attributes.siblingSeq);
	      w.show();
       	  ipr = 2; 
       	  bipr = false; 
       	  } 
    }

    function sortdel()
    {
      if(selNode == null)
       	return;
       Ext.MessageBox.confirm('确认', '请确认是否删除,删除后不可恢复!', delShowResultText);
    
     }
    
      tree = new Tree.TreePanel({
        el:'leftTree',
		autoScroll:true,
		root:root,
		animate:true,
		enableDD:true,
		autoHeight :true,
		border:false,
		rootVisible:true,
		allowDrag:true,
		containerScroll: true,
        loader: new Tree.TreeLoader({
            dataUrl:'tagTree.htm',
            baseParams:{id:0,action:'listSorl'}
        })
    });

	tree.on("beforeload", function(treeLoader, node) {
	 	tree.loader.baseParams.id = treeLoader.id;
    }, this);
    /***把刚加上的子节点 属性 是否是节点设置成 false,不然不接受拖拽添加***/
    tree.on('append',function(tree,parent,node,index ){
    	node.leaf = false;
    });
   tree.on('beforemovenode',function(mytree,curNode, oldParent, newParent, index){
    	sortAjax("tagTree.htm",{sortId:curNode.id,parentSortId:newParent.id,action:'updateSort'},function(){},sortFail);  
    });
  
  
    // set the root node
    var root = new Tree.AsyncTreeNode({
        text: '课题分类',
        draggable:false,
        expandable: true,
        id:'0'

    });
    tree.setRootNode(root);

    // render the tree
    tree.render();
    root.expand();
    tree.on('contextmenu',prepareCtx);
   
     tree.on('click', function(node){
	     if(!node.hasChildNodes())
	     {
	     // accordion02.load('/pre/perInfo.do?perInfo=list&id='+node.id);
	     var url ='tagTree.htm?action=list&sortId='+node.id;
	      }
	       else{node.unselect();};
	});

   function prepareCtx(node, e){
        selNode = node;
        node.select();
        if(node.id != 0)
	    ctxMenu.showAt(e.getXY());
    }

	function fcm(id,cname,siblingSeq){
	
		if(selNode != null){
		  var i = selNode.attributes.tagType;
		  var icon;
		  var iconp;
		  	if(1 == i)
			{	
			icon="index/Images/news.gif";
			iconp ="index/Images/insms.gif" ;
			}	
			if(2 == i){
			icon="index/Images/colligation.gif";
			iconp = "index/Images/discuss.gif";
				}	
			if(3 == i){
			icon="index/Images/@voiture.gif";
			iconp = "index/Images/resource.gif" ;
				}	
			if(4 == i){
			icon="index/Images/my.gif";
			iconp = "index/Images/@express.gif";
				}	
					
			if(selNode.childNodes.length > 0)
			   icon = selNode.childNodes[0].getUI().getIconEl().src;
		  //alert(""+selNode..siblingSeq);
	    	var m1 = new Ext.tree.TreeNode({
	        text: cname,
	        draggable:true,
	        siblingSeq:siblingSeq,
	        id:id,
	        tagType:i,
	        icon:icon
	    	});			
	    	selNode.getUI().getIconEl().src = iconp;
	    	selNode.leaf=false;
	    	selNode.appendChild(m1);
		}
	}
});


function sortAjax(url,params,sucFn,faiFn){
	Ext.Ajax.request({
	   url: url,
	   success: sucFn,
	   failure: faiFn,
	   params: params
	});
}
